package com.xinli.framework.web.service;

import javax.annotation.Resource;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.google.gson.JsonObject;
import com.xinli.common.core.domain.model.BdPhoneBody;
import com.xinli.common.core.domain.model.LoginXcxBody;
import com.xinli.common.core.domain.model.RegisterXcxBody;
import com.xinli.common.utils.*;
import com.xinli.framework.security.OpenIdAuthenticationToken;
import com.xinli.framework.security.PhoneAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.xinli.common.constant.Constants;
import com.xinli.common.core.domain.entity.SysUser;
import com.xinli.common.core.domain.model.LoginUser;
import com.xinli.common.core.redis.RedisCache;
import com.xinli.common.exception.ServiceException;
import com.xinli.common.exception.user.CaptchaException;
import com.xinli.common.exception.user.CaptchaExpireException;
import com.xinli.common.exception.user.UserPasswordNotMatchException;
import com.xinli.common.utils.ip.IpUtils;
import com.xinli.framework.manager.AsyncManager;
import com.xinli.framework.manager.factory.AsyncFactory;
import com.xinli.system.service.ISysConfigService;
import com.xinli.system.service.ISysUserService;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysRegisterService registerService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
//        if (captchaOnOff) {
//            validateCaptcha(username, code, uuid);
//        }
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    public HashMap<String, String> loginXcx(LoginXcxBody vo) throws Exception {
        HashMap<String, String> hashMap = new HashMap<>();
        String username = vo.getUsername();
        // 通过微信登录
        if (!StringUtils.isEmpty(vo.getCode())) {
            // 获取openId
            Map<String, String> wxOpenId = WxUtils.getWxOpenId(vo.getCode());
            String unionId= wxOpenId.get("unionId");
            if (StringUtils.isEmpty(unionId)) {
                throw new ServiceException("unionId获取失败");
            }
            String openId= wxOpenId.get("openId");
            if (StringUtils.isEmpty(openId)) {
                throw new ServiceException("openId获取失败");
            }
//            String openId = vo.getOpenId();
            SysUser sysUser = userService.selectUserByUnionId(unionId);
            if (sysUser == null) {
                // 注册返回token
                RegisterXcxBody registerUser = new RegisterXcxBody();
                registerUser.setUnionId(unionId);
                registerUser.setOpenId(openId);
                // 绑定账号
                registerService.registerXcxByUnionId(registerUser);
                throw new ServiceException(unionId, 1);
            } else {
                if (StringUtils.isEmpty(sysUser.getPhonenumber())) {
                    throw new ServiceException(unionId, 1);
                }
                String token = this.loginByUnionId(unionId);
                hashMap.put("token", token);
            }
        } else {
            // 账号密码登录
//            SysUser sysUser = userService.selectUserByUserName(username);
//            if (sysUser == null) {
//                // 注册
//                RegisterXcxBody registerXcxBody = new RegisterXcxBody();
//                registerXcxBody.setUsername(username);
//                registerXcxBody.setPassword(vo.getPassword());
//                String errorMsg = registerService.registerXcx(registerXcxBody);
//                if (StringUtils.isNotEmpty(errorMsg)) {
//                    throw new ServiceException(errorMsg);
//                }
//                String token = this.tologinXcx(username, vo.getPassword());
//                hashMap.put("token", token);
//            } else {
//                String token = this.tologinXcx(username, vo.getPassword());
//                hashMap.put("token", token);
//            }
        }

        return hashMap;

    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }




    public String loginByUnionId(String unionId) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new OpenIdAuthenticationToken(unionId));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(unionId, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(unionId, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(unionId, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    public String loginByPhone(String phone,String password) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("phone", phone);
        jsonObject.set("password", password);

        // 用户验证
        Authentication authentication = null;
        try {

            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new PhoneAuthenticationToken(jsonObject.toString()));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    // 绑定手机号
    public void bindPhone(BdPhoneBody bdPhoneBody) {


    }


}
